package com.ruoyi.kenuo.service.impl;

import io.netty.handler.codec.mqtt.MqttProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Component
@Slf4j
public class MqttPublisher {

    @Resource
    private MqttClient mqttClient;

    @Value("${spring.mqtt.qos}")
    private int qos;



    /**
     * 发布MQTT消息
     * @param topic 主题
     * @param content 消息内容
     * @param retained 是否保留消息（服务器存储最后一条保留消息）
     */
    public void publish(String topic, String content, boolean retained) {
        try {
            if (mqttClient.isConnected()) {
                MqttMessage message = new MqttMessage(content.getBytes());
                message.setQos(qos);
                message.setRetained(retained);
                mqttClient.publish(topic, message);
                log.info("消息发布成功 - 主题: {}, 内容: {}", topic, content);
            } else {
                log.error("MQTT客户端未连接，发布失败");
            }
        } catch (MqttException e) {
            log.error("消息发布异常", e);
        }
    }

    // 简化方法（默认不保留消息）
    public void publish(String topic, String content) {
        publish(topic, content, false);
    }


    /**
     * 订阅某个主题
     * @param topic
     */
    public void subScribe(String topic) {
        try {
            if (mqttClient.isConnected()) {
                mqttClient.subscribe(topic);
                log.info("消息订阅成功 - 主题: {}", topic);
            } else {
                log.error("MQTT客户端未连接，发布失败");
            }
        } catch (MqttException e) {
            log.error("消息订阅异常", e);
        }
    }
    /**
     * 取消某个某个主题的订阅
     * @param topic
     */
    public void CancelSubScribe(String topic) {
        try {
            if (mqttClient.isConnected()) {
                mqttClient.unsubscribe(topic);
                log.info("取消订阅成功 - 主题: {}", topic);
            } else {
                log.error("MQTT客户端未连接，发布失败");
            }
        } catch (MqttException e) {
            log.error("消息订阅异常", e);
        }
    }

}
